package com.ken.elmssm.controller;

import com.ken.elmssm.bean.Admin;
import com.ken.elmssm.bean.Role;
import com.ken.elmssm.common.ElmException;
import com.ken.elmssm.common.Pager;
import com.ken.elmssm.common.Result;
import com.ken.elmssm.service.AdminService;
import com.ken.elmssm.service.RoleService;
import com.ken.elmssm.util.PasswordUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 *@RestController 的方法默认会返回json数据
 * @author ken
 */
@RestController
@RequestMapping("/sys/admin")
public class AdminController {
    private Logger logger = Logger.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("login")
    public Admin login(HttpServletRequest request, HttpServletResponse response) {
        Admin temp = new Admin();
        String adminName = request.getParameter("adminName");
        String password = request.getParameter("password");
        //获取用户输入的验证码
        String validate = request.getParameter("validate");

        Admin param = new Admin(null, adminName, password);
        try {
            String rand = (String) request.getSession().getAttribute("rand");
            // 使用验证码技术后，需要先校验验证码是否正确，在进行数据库校验；避免系统被机器暴露破解
            if (rand != null && rand.equals(validate)) {
                temp = adminService.login(param);
                // 进行md5+盐值算法判断
                if (temp != null && PasswordUtils.matches(temp.getSalt(), password, temp.getPassword())) {
                    param.setAdminId(temp.getAdminId());
                    // 数据库验证成功，保存用户的session会话跟踪中
                    request.getSession().setAttribute("login_user", temp);
                    // 用户登录成功后，使用cookie返回登录用户名称给客户端
                    Cookie cookie = new Cookie("login_user", temp.getAdminName());
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        } catch (ElmException e) {
            e.printStackTrace();
        }
        return temp;
    }

    @RequestMapping("add")
    public Result add(Admin admin, MultipartFile file1, HttpSession session) {
        Result result = new Result();
        // 用户选择了上传的文件
        if(file1 != null && file1.getSize() > 0){
            //获取或创建文件在服务器的保存路径
            String path = session.getServletContext().getRealPath("/");
            String uploadPath = "upload/images/";
            File pathFile = new File(path+uploadPath);
            pathFile.mkdirs();
            //修改上传后的文件名称
            String ofname = file1.getOriginalFilename();
            String fileType = ofname.substring(ofname.lastIndexOf("."));
            String newFileName = UUID.randomUUID()+fileType;
            logger.info(newFileName);
            File outputFile = new File(pathFile,newFileName);
            try {
                // 执行文件上传
                file1.transferTo(outputFile);
                // 上传成功，保存头像的相对地址
                admin.setHeadImage(uploadPath+newFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 新增用户时，生成随机盐值，并加密密码
        String salt = PasswordUtils.getSalt();
        String password = PasswordUtils.encode(admin.getPassword(),salt);
        // 把明文密码换成加密密码和加密盐一起更新
        admin.setSalt(salt);
        admin.setPassword(password);
        try {
            boolean ret = adminService.add(admin);
            if(ret) {
                result.setSuccess(true);
            }else {
                result.setMsg("新增管理员失败");
            }
        }catch (ElmException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("del")
    public Result delete(Integer adminId) {
        Result result = new Result();
        if(adminId != null) {
            try {
                boolean ret = adminService.deleteById(adminId);
                if(ret) {
                    result.setSuccess(Boolean.TRUE);
                    result.setMsg("删除成功");
                }else {
                    result.setMsg("删除失败");
                }
            }catch (ElmException e) {
                result.setMsg(e.getMessage());
            }
        }else {
            result.setMsg("用户不存在");
        }
        return result;
    }

    @RequestMapping("edit")
    public Result edit(Admin admin, MultipartFile file1, HttpSession session) {
        logger.info(" ------ " + admin);
        Result result = new Result();
        // 用户选择了上传的文件
        if (file1 != null && file1.getSize() > 0) {
            String path = session.getServletContext().getRealPath("/");
            logger.info(path);
            String uploadPath = "upload/images/";
            File pathFile = new File(path + uploadPath);
            logger.info(pathFile);
            pathFile.mkdirs();
            String ofname = file1.getOriginalFilename();
            String fileType = ofname.substring(ofname.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + fileType;
            File outputFile = new File(pathFile, newFileName);
            try {
                // 执行文件上传
                file1.transferTo(outputFile);
                // 上传成功，保存头像的相对地址
                admin.setHeadImage(uploadPath + newFileName);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            Admin temp = adminService.findById(admin.getAdminId());
            if (temp != null) {
                // 修改用户时，同时更新盐值和重新加密密码
                String salt = PasswordUtils.getSalt();
                String password = PasswordUtils.encode(admin.getPassword(), salt);
                temp.setSalt(salt);
                temp.setPassword(password);
                // 修改管理员的角色
                temp.setRoles(admin.getRoles());
                if(admin.getHeadImage()!=null) {
                    temp.setHeadImage(admin.getHeadImage());
                }

                boolean ret = adminService.edit(temp);
                if (ret) {
                    result.setSuccess(true);
                } else {
                    result.setMsg("修改管理员失败");
                }
            } else {
                result.setMsg("数据不存在");
            }

        } catch (ElmException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("search")
    public Pager<Admin> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "rows", defaultValue = "10") Integer size) {
        Pager<Admin> pager = new Pager<>(page,size);
        logger.info(pager);
        int total = adminService.findTotal(pager);
        List<Admin> list = adminService.findByPager(pager);
        pager.setRows(list);
        pager.setTotal(total);
        logger.info(pager);
        return pager;
    }

    @RequestMapping("rolelist")
    public List<Role> findRoleFromAdmin() {
        List<Role> list = roleService.findByPager(null);
        return list;
    }

    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response)  throws IOException{
        // 使用会话失效，取消所有会话跟踪信息
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/login.html");
    }

    @RequestMapping("udpass")
    private Result updatePassword(HttpServletRequest request, HttpServletResponse response)  throws IOException{
        String password = request.getParameter("opassword");
        String npassword = request.getParameter("npassword");
        Admin admin = (Admin)request.getSession().getAttribute("login_user");
        Result result = new Result();
        try {
            // 先校验原密码，通过后才能修改密码
            if(admin != null && PasswordUtils.matches(admin.getSalt(), password, admin.getPassword())) {
                // 更新密码时，同时更新盐值和重新加密密码
                String salt = PasswordUtils.getSalt();
                password = PasswordUtils.encode(npassword, salt);
                admin.setPassword(password);
                admin.setSalt(salt);
                boolean ret = adminService.edit(admin);
                if(ret) {
                    result.setSuccess(true);
                    this.logout(request,response);
                }else {
                    result.setMsg("修改管理员密码失败");
                }
            }else {
                result.setMsg("原密码不正确");
            }

        }catch(ElmException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
//        WebUtil.writeJsonToClient(response, admin);
        return result;
    }




}
